'use strict';
/**
 * Created by three on 14-7-15.
 */

/**
 * app中使用的restful接口服务定义
 * create：工厂方法
 *      serviceModule：创建的module
 *      apiDef：api定义，格式：
 *              {
     *                  name:'',                            // service名称
     *                  url:'/system/func/:id',             // api url
     *                  type:'restful',                     // 实现方式：restful->$resource | http->$http
     *                  data:{id:'@id'},                    // 定义url数据替换，默认{id:'@id'}。http方式不支持
     *                  methods: {                          // 请求方法定义，默认 add[POST] delete[DELETE] get[GET] update[PUT] list[GET]
     *                      update: {                       // 调用方法名
     *                          method: 'PUT',              // 请求方法
     *                          params: {},                 // 默认参数
     *                          isArray: false              // 返回数据是否数组【true：数组；false：一般对象】
     *                      }
     *                  }
 *              }
 */
(function (app) {
    app.provider('RestFulServiceFactory', ["FactoriesProvider", function (FactoriesProvider) {
        var factory = this;
        var defaultData = {id: '@id'};
        var defaultMethods = {
            update: {method: 'PUT', params: {}, isArray: false},
            add: {method: 'POST', params: {}, isArray: false},
            list: {method: 'GET', params: {}, isArray: true},
            get: {method: 'GET', params: {}, isArray: false},
            delete: {method: 'DELETE', params: {}, isArray: false}
        };
        factory.create = function (restfulConf) {
            for (var i = 0; i < restfulConf.length; i++) {

                (function (apiDef) {
                    var injectParams = ['$resource', '$http'];
                    var serviceFun = function ($resource, $http) {
                        return (function (serviceDef) {
                            if (serviceDef.type == 'restful') { // restful api
                                var data = serviceDef.data || defaultData;
                                // 配置请求方法
                                var realMethods = JSON.parse(JSON.stringify(defaultMethods));
                                for (var method in serviceDef.methods) {
                                    realMethods[method] = serviceDef.methods[method];
                                }
                                return $resource(serviceDef.url, data, realMethods);
                            } else if (serviceDef.type == 'http') {
                                var serv = {};
                                var realMethods = JSON.parse(JSON.stringify(defaultMethods));
                                for (var method in serviceDef.methods) {
                                    realMethods[method] = serviceDef.methods[method];
                                }
                                for (var method in realMethods) {
                                    var methodConf = realMethods[method];
                                    serv[method] = function (data, suc_cb, err_cb) {

                                        $http({
                                            method: methodConf.method,
                                            url: serviceDef.url + (methodConf.url || ''),
                                            params: methodConf.params || {},
                                            data: data
                                        }).
                                            success(function (data, status, headers, config) {
                                                suc_cb(data, status, headers, config);
                                            }).
                                            error(function (data, status, headers, config) {
                                                err_cb(data, status, headers, config);
                                            });
                                    };
                                }
                                return serv;
                            }
                        }(apiDef));
                    };

                    serviceFun.$inject = injectParams;
                    FactoriesProvider.ServiceFactory.create(apiDef.name, serviceFun);
                }(restfulConf[i]));
            }
        };
        factory.$get = function () {
            return function () {
                return null;
            };
        }
    }]);
}(angular.module('app.common.factory')));

